﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace WellDone
{
    public sealed partial class TimeClockDialog : Page
    {
        public bool bPunchedIn = false;
        public event EventHandler CloseRequested;
        public TimeClockDialog()
        {
            this.InitializeComponent();
            DispatcherTimer dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1 second
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Start();
        }

        private async void dispatcherTimer_Tick(object sender, object e)
        {
            await DisplayCurrentTime();
        }

        async Task<DateTime> DisplayCurrentTime()
        {
            DateTime dtNow = await Globals.Now();
            txtCurrentTime.Text = dtNow.ToString("h:mm:ss tt");
            return dtNow;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            init();
        }

        public async void init()
        {
            Globals.TimeSheetRecords = await Globals.client.GetTimeSheetObjectsAsync(Globals.token, "");            
            cmbRoles.Items.Clear();            
            foreach (ServiceReferenceOpenRPOS.EmployeeRole employeeRole in Globals.EmployeeRoleRecords)
            {
                foreach (ServiceReferenceOpenRPOS.Role role in Globals.RoleRecords)
                {
                    if (employeeRole.col_RoleID == role.col_ID)
                    {
                        cmbRoles.Items.Add(role.col_Title);
                        break;
                    }
                }
            }

            if (cmbRoles.Items.Count>0)
            {
                cmbRoles.SelectedIndex = 0;
            }

            updatePunchStatus();

            if (cmbRoles.IsEnabled==false)
            {
                btnPunchInOut.Focus(FocusState.Pointer);
            }
            else
            {
                cmbRoles.Focus(FocusState.Pointer);
            } 
        }

        private async void updatePunchStatus()
        {
            // Determine the login status of the current employee
            DateTime dtNow = await Globals.Now();
            IEnumerable<ServiceReferenceOpenRPOS.TimeSheet> query = Globals.TimeSheetRecords.Where(x => x.col_EmployeeID == Globals.currentLogin.col_ID && x.col_PunchDateTime.Date == dtNow.Date && x.col_Adjusted == false);
            
            bPunchedIn = false;
            if (query.Count() > 0)
            {
                if (query.Last().col_PunchType)
                {
                    if (cmbRoles.Items.Count() > 0)
                    {
                        cmbRoles.SelectedItem = Globals.RoleRecords.Where(x => x.col_ID == query.Last().col_RoleID).First().col_Title;
                    }
                    bPunchedIn = true;
                }
            }
            if (bPunchedIn)
            {
                btnPunchInOut.Content = Globals.k_str_punch_out;
                cmbRoles.IsEnabled = false; 
            }
            else
            {
                btnPunchInOut.Content = Globals.k_str_punch_in;
                cmbRoles.IsEnabled = true;
            }

            LayoutRoot.Visibility = Visibility.Visible;
        }

        private async void btnPunchInOut_Click(object sender, RoutedEventArgs e)
        {
            ServiceReferenceOpenRPOS.TimeSheet timeSheet = new ServiceReferenceOpenRPOS.TimeSheet();
            if (bPunchedIn) // Prompt the user to punch-out
            {
                timeSheet.bFilterPunchType = true;
                timeSheet.col_PunchType = false; // Out-punch
                timeSheet.bFilterEmployeeID = true;
                timeSheet.col_EmployeeID = Globals.currentLogin.col_ID;
                timeSheet.bFilterPunchDateTime = true;
                timeSheet.col_PunchDateTime = await Globals.Now();
                await Globals.client.AddTimeSheetObjectAsync(Globals.token, timeSheet);
                btnPunchInOut.Content = Globals.k_str_punch_in;
                bPunchedIn = false;
                cmbRoles.IsEnabled = true;
            }
            else
            {
                // Prompt the user to punch-In
                timeSheet.bFilterPunchType = true;
                timeSheet.col_PunchType = true; // In-punch
                timeSheet.bFilterEmployeeID = true;
                timeSheet.col_EmployeeID = Globals.currentLogin.col_ID;
                timeSheet.bFilterPunchDateTime = true;
                timeSheet.col_PunchDateTime = await Globals.Now();
                timeSheet.bFilterRoleID = true;
                timeSheet.col_RoleID = Globals.RoleRecords.Where(x => x.col_Title == (string)cmbRoles.SelectedValue).First().col_ID;
                await Globals.client.AddTimeSheetObjectAsync(Globals.token, timeSheet);
                btnPunchInOut.Content = Globals.k_str_punch_out;
                bPunchedIn = true;
                cmbRoles.IsEnabled = false;
            }
        }

        private void btnMenu_Click(object sender, RoutedEventArgs e)
        {
            // Navigate to the main page...
            Frame rootFrame = Window.Current.Content as Frame;
            rootFrame.Navigate(typeof(MainPage), e);
            // Close the dialog
            if (this.CloseRequested != null)
            {
                this.CloseRequested(this, EventArgs.Empty);
            }
        }

        private void btnLogout_Click(object sender, RoutedEventArgs e)
        {
            // Return to the login screen...
            Frame rootFrame = Window.Current.Content as Frame;
            rootFrame.Navigate(typeof(Login), e);
            // Close the dialog
            if (this.CloseRequested != null)
            {
                this.CloseRequested(this, EventArgs.Empty);
            }
        }
    }
}
